import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Upload, Icon, message } from 'antd';
import { api } from '../../utils/config.js';
const styles = {
  img: {
    width: "100%",
    height: "100%",
  },
  img1: {
    width:'100px',
    height:'100px'
  },
  load: {

  },
  upload: {
    marginTop: -30,
    overflow: "hidden"
  }
}
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
function beforeUpload(file) {
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过2MB!');
  }
  return isLt2M;
}

class Avatar extends React.Component {
  state = {
    loading: false,
    imageUrl:'',
    img:''
  };
  componentWillMount(){
    this.setState({
      imageUrl:this.props.imageUrl
    })
  }
  handleChange = (info) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // console.log(info)
      const img = info.file.response.data;
      this.props.onChange(img);
      getBase64(info.file.originFileObj, imageUrl => {
        this.setState({
          imageUrl,
          loading: false,
        })
      });
    }
  }
  render() {
    const uploadButton = (
      <div style={styles.load}>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text" style={styles.upload}>上传头像</div>
      </div>
    );
    const {imageUrl} = this.state;
    // console.log(imageUrl)
    const headers = {
      Authorization: localStorage.getItem("access_token")
    }
    return (
      <Upload
        name="file"
        accept="image*/*"
        listType="picture-card"
        className="avatar-uploader image"
        showUploadList={false}
        action={api.uploadPic}
        beforeUpload={beforeUpload}
        onChange={this.handleChange}
        style={styles.img1}
        headers={headers}
      >
        {imageUrl===''||imageUrl? <img src={(imageUrl === '') ? imgLogo : imageUrl} alt="avatar" style={styles.img} /> : uploadButton}
      </Upload>
    );
  }
}
export default Avatar;
